package com.redoor.iot.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.redoor.iot.mapper.UserMapper;
import com.redoor.iot.mapper.UserRoleRelaMapper;
import com.redoor.iot.model.User;
import com.redoor.iot.model.UserRoleRela;
import com.redoor.iot.service.IMailService;
import com.redoor.iot.service.IUserService;

@Service("userService")
public class UserServiceImpl implements IUserService {
	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private UserRoleRelaMapper userRoleRelaMapper;
	
	@Autowired
	private IMailService mailService;
	
	
	@Override
	public List<User> list(Map<String, Object> map) {
		return userMapper.list(map);
	}

	@Override
	public int count(Map<String, Object> map) {
		return userMapper.count(map);
	}
	
	@Transactional
	@Override
	public int save(User user) {
		int count = userMapper.save(user);
		Long userId = user.getUserId();
		List<Long> roles = user.getRoleIds();
		userRoleRelaMapper.removeByUserId(userId);
		List<UserRoleRela> list = new ArrayList<>();
		for (Long roleId : roles) {
			UserRoleRela ur = new UserRoleRela();
			ur.setUserId(userId);
			ur.setRoleId(roleId);
			list.add(ur);
		}
		if (list.size() > 0) {
			userRoleRelaMapper.batchSave(list);
		}
		
		//发送激活邮件给用户
		String content="<html>\n" +
                "<body>\n" +
                "    <h3>hello world ! 这是一封html激活邮件!</h3>\n" +
                "    <h3>激活码:"+user.getActiveCode()+"</h3>\n" +
                "</body>\n" +
                "</html>";
        mailService.sendHtmlMail(user.getEmail(),"test simple mail",content);
		
		return count;
	}
	
	@Override
	public User get(Long id) {
		List<Long> roleIds = userRoleRelaMapper.listRoleId(id);
		User user = userMapper.get(id);
		user.setRoleIds(roleIds);
		return user;
	}
	
	@Transactional
	@Override
	public int update(User user) {
		int r = userMapper.update(user);
		Long userId = user.getUserId();
		List<Long> roles = user.getRoleIds();
		userRoleRelaMapper.removeByUserId(userId);
		List<UserRoleRela> list = new ArrayList<>();
		if(!CollectionUtils.isEmpty(roles)) {
			for (Long roleId : roles) {
				UserRoleRela ur = new UserRoleRela();
				ur.setUserId(userId);
				ur.setRoleId(roleId);
				list.add(ur);
			}
		}
		if (list.size() > 0) {
			userRoleRelaMapper.batchSave(list);
		}
		return r;
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	

}
